package com.zmh.service.time;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zmh.common.PackageUtil;
import com.zmh.dao.QuartzMapper;
import com.zmh.entity.QuartzEntity;
@Service
public class JobService {
	private final static Logger LOGGER = LoggerFactory
			.getLogger(JobService.class);
	@Autowired
	private QuartzMapper quartzMapper;
	@Autowired
	private Scheduler scheduler;

	/**
	 * 增加job
	 * 
	 * @return: int
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午11:29:46
	 * @Description:
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	public int scheduleJob(QuartzEntity quartz) {
		LOGGER.info("新增任务");
		try {
			// 如果是修改 展示旧的 任务
			if (quartz.getOldJobGroup() != null) {
				JobKey key = new JobKey(quartz.getOldJobName(),
						quartz.getOldJobGroup());
				scheduler.deleteJob(key);
			}
			Class cls = Class.forName(quartz.getJobClassName());
			cls.newInstance();
			// 构建job信息
			JobDetail job = JobBuilder.newJob(cls)
					.withIdentity(quartz.getJobName(), quartz.getJobGroup())
					.withDescription(quartz.getDescription()).build();
			// 触发时间点
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder
					.cronSchedule(quartz.getCronExpression());
			Trigger trigger = TriggerBuilder.newTrigger()
					.withIdentity("trigger" + quartz.getJobName(),
							quartz.getJobGroup())
					.startNow().withSchedule(cronScheduleBuilder).build();
			// 交由Scheduler安排触发
			scheduler.scheduleJob(job, trigger);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 触发定时任务
	 * 
	 * @return: boolean
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午11:32:58
	 * @Description:
	 */
	public boolean triggerJob(QuartzEntity quartz) {
		LOGGER.info("触发任务");
		try {
			JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
			scheduler.triggerJob(key);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 停止定时任务
	 * 
	 * @return: boolean
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午11:40:46
	 * @Description:
	 */
	public boolean pauseJob(QuartzEntity quartz) {
		LOGGER.info("停止任务");
		try {
			JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
			scheduler.pauseJob(key);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 恢复定时任务
	 * 
	 * @return: boolean
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午11:41:25
	 * @Description:
	 */
	public boolean resumeJob(QuartzEntity quartz) {
		LOGGER.info("恢复任务");
		try {
			JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
			scheduler.resumeJob(key);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean deleteJob(QuartzEntity quartz) {
		LOGGER.info("移除任务");
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(),
					quartz.getJobGroup());
			// 停止触发器
			scheduler.pauseTrigger(triggerKey);
			// 移除触发器
			scheduler.unscheduleJob(triggerKey);
			// 删除任务
			scheduler.deleteJob(
					JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
			System.out
					.println("removeJob:" + JobKey.jobKey(quartz.getJobName()));
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * 分页查询cron类型任务列表
	 * 
	 * @return: List<QuartzEntity>
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午9:40:48
	 * @Description:
	 */
	public List<QuartzEntity> getAllByCron(Integer pageNo, Integer pageSize) {
		// 页码转换
		int begin = (pageNo - 1) * pageSize;
		return quartzMapper.getAllByCron(begin, pageSize);
	}
	/**
	 * 查询cron类型任务总数
	 * 
	 * @return: Long
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月30日 上午9:41:33
	 * @Description:
	 */
	public int getCountByCron() {
		return quartzMapper.getCountByCron();
	}
	/**
	 * 初始化，重置所有的定时任务
	 * 
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年8月10日 上午11:09:10
	 * @Description:
	 */
	@PostConstruct
	public void init() {
		// 获取所有的job
		List<String> classNames = PackageUtil
				.getClassName("com.zmh.service.time.job", false);
		System.out.println(JSON.toJSONString(classNames));
		// 获取所有数据库中的并删除
		List<QuartzEntity> qList = getAllByCron(1, 999);
		for (QuartzEntity quartz : qList) {
			System.out.println("移除任务：" + quartz.getJobName());
			deleteJob(quartz);
		}
		// 增加所有job
		for (String className : classNames) {
			System.out.println("增加任务：" + className);
			String jobName = className
					.substring(className.lastIndexOf(".") + 1);
			String cron = "";
			switch (jobName) {
				case "WorkLogSYTimer" :
					cron = "0 30 8 * * ?";
					break;
				case "WorkLogWYTimer" :
					cron = "0 30 20 * * ?";
					break;
				case "WorkPunchAmTimer" :
					 cron = "30 30 8 * * ?";
					break;
				case "WorkPunchPmTimer" :
					 cron = "0 30 21 * * ?";
					break;
				case "SendMailTimer" :
					cron = "0/3 * * * * ?";
					break;
				case "OamsgTimer" :
					cron = "0 0/30 * * * ?";
					break;
				default :
					cron = "0 0/5 * * * ?";
					break;
			}
			scheduleJob(new QuartzEntity(jobName, "myJob", "", className, cron,
					jobName));
		}
	}
}
